﻿/*
 DotNetNuke - http://www.dotnetnuke.com
 Copyright (c) 2002-2010 by DotNetNuke Corp.

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Web.Hosting;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Xsl;

using DotNetNuke.Common;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Modules.UserDefinedTable.Security;
using DotNetNuke.Security;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Skins;
using DotNetNuke.UI.Skins.Controls;
using DotNetNuke.UI.UserControls;
using DotNetNuke.UI.WebControls;




namespace DotNetNuke.Modules.UserDefinedTable
{

  /// <summary>
  /// Displays List style UI of the UserDefinedTable
  /// </summary>
  public partial class List : UDTdataEditor, IActionable, IPostBackEventHandler
  {



    #region searchManager

    private class SearchManager
    {



      private enum SearchControlTypes
      {
        Columns = 1,
        Operator = 2,
        Search = 3
      }



      //[AccessedThroughProperty("cmdResetSearch")]
      //private LinkButton _cmdResetSearch;
      //[AccessedThroughProperty("cmdSearch")]
      //private LinkButton _cmdSearch;
      
      private List parent;
      private PlaceHolder searchPlaceHolder;




      public SearchManager(List parent)
      {
        this.parent = parent;
        this.cmdSearch = parent.cmdSearch;
        this.cmdResetSearch = parent.cmdResetSearch;
        this.searchPlaceHolder = parent.phSearchSentence;

        //event handlers
        cmdSearch.Click += new EventHandler(cmdSearch_Click);
        cmdResetSearch.Click +=new EventHandler(cmdResetSearch_Click);

      }




      private void cmdResetSearch_Click(object sender, EventArgs evt)
      {
        if (!this.parent.RenderMethod.StartsWith("UDT_Xsl"))
        {
          this.Reset();
          this.parent.CurrentPage = 1;
          this.IsSearching = false;
        }
        else
          this.parent.Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(this.parent.TabId));
        
      }





      private void cmdSearch_Click(object sender, EventArgs evt)
      {
        if (!this.parent.RenderMethod.StartsWith("UDT_Xsl"))
        {
          this.parent.CurrentPage = 1;
          this.IsSearching = true;
        }
        else
        {
          List<string> list = new List<string>();
          int moduleId = this.parent.ModuleId;

          if (!string.IsNullOrEmpty(this.TxtSearch.Text))
          {
            list.Add(string.Format("u{0}q={1}", moduleId, Utilities.UrlHexEncode(this.TxtSearch.Text)));
            if (!Utilities.CBoolN((this.parent.ModuleContext.Settings[SettingName.SimpleSearch]), false))
            {
              list.Add(string.Format("u{0}c={1}", moduleId, Utilities.UrlHexEncode(this.DrpSearchableColumns.SelectedValue)));
              list.Add(string.Format("u{0}m={1}", moduleId, this.DrpSearchMode.SelectedValue));
            }
            string url = DotNetNuke.Common.Globals.NavigateURL(this.parent.TabId, "", list.ToArray());
            this.parent.Response.Redirect(url);
          }
        }
      }





      public bool DataBindingNeeded()
      {

        bool isSearchable = false;

        foreach (DataRow row in this.parent.DataSet.Tables[DataSetTableName.Data].Rows)
          if (Convert.ToBoolean(row[FieldsTableColumn.Searchable]))
          {
            isSearchable = true;
            break;
          }

        if (isSearchable)
        {
          this.parent.panSearch.Visible = true;

          if (!Utilities.CBoolN((this.parent.ModuleContext.Settings[SettingName.SimpleSearch]), false))
            this.parent.plSearch.Visible = false;
          
          else
          {
            foreach (Control ctl in this.searchPlaceHolder.Controls)
            {
              if (ctl.ID == "txtSearch")
                ctl.Visible = true;

              else
                ctl.Visible = false;
            }

          }
          if (!this.IsSearching && !Utilities.CBoolN((this.parent.ModuleContext.Settings[SettingName.ShowNoRecordsUntilSearch]), false))
            this.IsSearching = true;

        }
        this.parent.cmdResetSearch.Visible = (this.TxtSearch.Text != "") | (this.DrpSearchMode.SelectedValue != "contain");

        if ((isSearchable && !this.IsSearching) && (this.TxtSearch.Text == ""))
          return false;

        return true;
      }





      private static string EscapeSearchInput(string input)
      {
        return input.Replace("'", "''");
      }




      public string Filter()
      {
        string str2 = string.Empty;

        if ( string.IsNullOrEmpty(this.TxtSearch.Text) )
          return string.Empty;
        
        DataSet dataSet = this.parent.DataSet;

        foreach (DataRow current in this.parent.DataSet.Tables[DataSetTableName.Fields].Rows)
        {
          if (this.TxtSearch.Visible && Convert.ToBoolean(current[FieldsTableColumn.Searchable]))
          {
            string str4 = (string)current[FieldsTableColumn.Title];

            if ((this.DrpSearchableColumns.SelectedValue == "allcolumns") | (this.DrpSearchableColumns.SelectedValue == str4))
            {
              if ( !string.IsNullOrEmpty(str2) )
                str2 = str2 + " OR ";

              if (Utilities.CBoolN((this.parent.ModuleContext.Settings[SettingName.URLSearch]), false) && dataSet.Tables[DataSetTableName.Data].Columns.Contains(str4 + DataTableColumn.Appendix_Url))
                str4 = str4 + DataTableColumn.Appendix_Url;

              else if (dataSet.Tables[DataSetTableName.Data].Columns.Contains(str4 + DataTableColumn.Appendix_Caption))

                str4 = str4 + DataTableColumn.Appendix_Caption;

              if (dataSet.Tables[DataSetTableName.Data].Columns[str4].DataType == typeof(string))
                str2 = str2 + string.Format("([{0}] Like '[UDT:Search]')", str4);

              else
                str2 = str2 + string.Format("(Convert([{0}], 'System.String') Like '[UDT:Search]')", str4);

            }
          }
        }

        string text = this.TxtSearch.Text;

        if (this.DrpSearchMode.Visible)
        {
          switch (this.DrpSearchMode.SelectedValue)
          {
            case "contain":
              text = string.Format("*{0}*", text);
              break;

            case "startwith":
              text = string.Format("{0}*", text);
              break;

            case "endwith":
              text = string.Format("*{0}", text);
              break;
          }
        }
        else if (text.StartsWith("|") & text.EndsWith("|"))
          text = text.Substring(1, text.Length - 2);

        else if (text.StartsWith("|"))
          text = string.Format("{0}*", text.Substring(1));

        else if (text.EndsWith("|"))
          text = string.Format("*{0}", text.Substring(0, text.Length - 1));

        else
          text = string.Format("*{0}*", text);

        return str2.Replace("[UDT:Search]", EscapeSearchInput(text));
      }





      private void LoadColumns()
      {
        this.DrpSearchableColumns.Items.Clear();
        this.DrpSearchableColumns.Items.Add(new ListItem(DotNetNuke.Services.Localization.Localization.GetString("AllColumns", this.parent.LocalResourceFile), "allcolumns"));
        string text = string.Empty;

        foreach(DataRow current in this.parent.DataSet.Tables[DataSetTableName.Fields].Rows)
        {
          if (Convert.ToBoolean(current[FieldsTableColumn.Searchable]))
          {
            text = (string)current[FieldsTableColumn.Title];
            if (text != "allcolumns")
              this.DrpSearchableColumns.Items.Add(new ListItem(text, text));
            
          }
        }

        if (this.DrpSearchableColumns.Items.Count == 2)
        {
          this.DrpSearchableColumns.Items.RemoveAt(0);
          this.DrpSearchableColumns.Visible = false;
          Label label = (Label)this.searchPlaceHolder.FindControl("lblSearchableColumn");
          label.Text = text;
          label.Visible = true;
        }
      }





      public void LoadControls()
      {

        this.searchPlaceHolder.Controls.Clear();
        string pattern = @"(?<=\{)(?<control>\d)(?=\})|(?<text>[^\{\}]+)";

        foreach (Match current in new Regex(pattern).Matches(DotNetNuke.Services.Localization.Localization.GetString("SearchSentence", this.parent.LocalResourceFile)))
        {
          if ( !string.IsNullOrEmpty(Utilities.CStrN(current.Result("${text}"), "")) )
            this.searchPlaceHolder.Controls.Add(new LiteralControl(current.Result("${text}")));

          if ( !string.IsNullOrEmpty(Utilities.CStrN(current.Result("${control}"), "")) )
          {
            SearchControlTypes controlType = (SearchControlTypes)int.Parse(current.Result("${control}"));
            this.SearchControl(controlType);
          }
        }

        this.SearchControl(SearchControlTypes.Columns);
        this.SearchControl(SearchControlTypes.Operator);
        this.SearchControl(SearchControlTypes.Search);
      }





      public void Reset()
      {
        this.TxtSearch.Text = "";
        this.DrpSearchMode.SelectedValue = "contain";
        this.DrpSearchableColumns.SelectedIndex = 0;
      }





      private Control SearchControl(SearchControlTypes ControlType)
      {
        DropDownList list5;
        int moduleId = this.parent.ModuleId;
        switch (ControlType)
        {
          case SearchControlTypes.Columns:
            {
              DropDownList list = (DropDownList)this.searchPlaceHolder.FindControl("drpSearchableColumns");
              if (list == null)
              {
                list5 = new DropDownList();
                list5.ID = "drpSearchableColumns";
                list5.CssClass = "NormalTextBox";
                DropDownList child = list5;
                this.searchPlaceHolder.Controls.Add(child);
                Label label2 = new Label();
                label2.ID = "lblSearchableColumn";
                Label label = label2;
                label.Font.Bold = true;
                label.Visible = false;
                this.searchPlaceHolder.Controls.Add(label);
                this.LoadColumns();
                list = child;

                if (!string.IsNullOrEmpty(this.parent.Request.QueryString[string.Format("u{0}c", moduleId)]))
                  list.SelectedValue = Utilities.UrlHexDecode(this.parent.Request.QueryString[string.Format("u{0}c", moduleId)]);
                
              }
              return list;
            }
          case SearchControlTypes.Operator:
            {
              DropDownList list3 = (DropDownList)this.searchPlaceHolder.FindControl("drpSearchMode");

              if (list3 == null)
              {
                list5 = new DropDownList();
                list5.ID = "drpSearchMode";
                list5.CssClass = "NormalTextBox";
                DropDownList list4 = list5;
                list4.Items.Add(new ListItem(DotNetNuke.Services.Localization.Localization.GetString("SearchMode.Contain", this.parent.LocalResourceFile), "contain"));
                list4.Items.Add(new ListItem(DotNetNuke.Services.Localization.Localization.GetString("SearchMode.StartWith", this.parent.LocalResourceFile), "startwith"));
                list4.Items.Add(new ListItem(DotNetNuke.Services.Localization.Localization.GetString("SearchMode.EndWith", this.parent.LocalResourceFile), "endwith"));
                list4.Items.Add(new ListItem(DotNetNuke.Services.Localization.Localization.GetString("SearchMode.Equal", this.parent.LocalResourceFile), "equal"));
                this.searchPlaceHolder.Controls.Add(list4);
                list3 = list4;
                
                if (!string.IsNullOrEmpty(this.parent.Request.QueryString[string.Format("u{0}m", moduleId)]))
                  list3.SelectedValue = this.parent.Request.QueryString[string.Format("u{0}m", moduleId)];
                
              }
              return list3;
            }
          case SearchControlTypes.Search:
            {
              TextBox box = (TextBox)this.searchPlaceHolder.FindControl("txtSearch");
              if (box == null)
              {
                box = new TextBox();
                box.ID = "txtSearch";
                this.searchPlaceHolder.Controls.Add(box);
                
                if (!string.IsNullOrEmpty(this.parent.Request.QueryString[string.Format("u{0}q", moduleId)]))
                  box.Text = Utilities.UrlHexDecode(this.parent.Request.QueryString[string.Format("u{0}q", moduleId)]);
                
              }
              return box;
            }
        }
        return null;
      }



      private LinkButton cmdResetSearch
      { get; set; }



      //private LinkButton cmdResetSearch
      //{
      //  get
      //  {
      //    return this._cmdResetSearch;
      //  }
      //  [MethodImpl(MethodImplOptions.Synchronized)]
      //  set
      //  {
      //    EventHandler handler = new EventHandler(this.cmdResetSearch_Click);
      //    if (this._cmdResetSearch != null)
      //      this._cmdResetSearch.Click -= handler;

      //    this._cmdResetSearch = value;
      //    if (this._cmdResetSearch != null)
      //      this._cmdResetSearch.Click += handler;

      //  }
      //}




      private LinkButton cmdSearch
      { get; set; }




      //private LinkButton cmdSearch
      //{
      //  get
      //  {
      //    return this._cmdSearch;
      //  }
      //  [MethodImpl(MethodImplOptions.Synchronized)]
      //  set
      //  {
      //    EventHandler handler = new EventHandler(this.cmdSearch_Click);
      //    if (this._cmdSearch != null)
      //    {
      //      this._cmdSearch.Click -= handler;
      //    }
      //    this._cmdSearch = value;
      //    if (this._cmdSearch != null)
      //    {
      //      this._cmdSearch.Click += handler;
      //    }
      //  }
      //}




      private DropDownList DrpSearchableColumns
      {
        get
        {
          return (DropDownList)this.SearchControl(SearchControlTypes.Columns);
        }
      }




      private DropDownList DrpSearchMode
      {
        get
        {
          return (DropDownList)this.SearchControl(SearchControlTypes.Operator);
        }
      }





      public bool IsSearching
      {
        get
        {
          return (Utilities.CBoolN((this.parent.ViewState["IsSearching"]), false) | !string.IsNullOrEmpty(this.parent.Request.QueryString[string.Format("u{0}q", this.parent.ModuleId)]));
        }
        set
        {
          this.parent.ViewState["IsSearching"] = value;
        }
      }





      private TextBox TxtSearch
      {
        get
        {
          return (TextBox)this.SearchControl(SearchControlTypes.Search);
        }
      }




    }

    #endregion searchManager




    private UserDefinedTableController _udtController;
    private System.Data.DataSet objDataSet;
    private SearchManager search;



    //public List()
    //{
    //  //base.Init += new EventHandler(this.Page_Init);
    //  //base.Load += new EventHandler(this.Page_Load);
    //  //base.PreRender += new EventHandler(this.Page_PreRender);
    //}




    protected override void OnInit(EventArgs evt)
    {
      base.OnInit(evt);

      base.ModuleContext.HelpURL = string.Format("http://www.dotnetnuke.com/{0}?tabid=457", "Default.aspx");
      try
      {
        this.search = new SearchManager(this);
        this.search.LoadControls();
      }
      catch (Exception e)
      {
        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
      }

      ctlPagingControl.PageChanged += new EventHandler(ctlPagingControl_CurrentPageChanged);
      grdData.Sorting += new GridViewSortEventHandler(grdData_Sorting);
    }





    //private void Page_Init(object sender, EventArgs evt)
    //{
    //  base.ModuleContext.HelpURL = string.Format("http://www.dotnetnuke.com/{0}?tabid=457", "Default.aspx");
    //  try
    //  {
    //    this.search = new SearchManager(this);
    //    this.search.LoadControls();
    //  }
    //  catch (Exception e)
    //  {
    //    Exception exc = e;
    //    DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
    //  }
    //}





    //protected void Page_Load(object sender, EventArgs evt)
    protected override void OnLoad(EventArgs evt)
    {
      base.OnLoad(evt);

      try
      {
        if (!this.IsPostBack)
          this.CurrentPage = 1;
        
      }
      catch (Exception e)
      {
        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException((PortalModuleBase)this, exc);
      }
    }





    //protected void Page_PreRender(object sender, EventArgs evt)
    protected override void OnPreRender(EventArgs evt)
    {
      base.OnPreRender(evt);

      grdData.RowDataBound += new GridViewRowEventHandler(grdData_RowDataBound);
      //grdData.Sorting += new GridViewSortEventHandler(grdData_Sorting);

      try
      {
        this.BindData();
      }
      catch (Exception e)
      {
        Exception exc = e;
        this.HandleException(exc, DotNetNuke.Services.Localization.Localization.GetString("DataBindingFailed.ErrorMessage", this.LocalResourceFile));
      }
    }




    private void BindData()
    {

      System.Web.HttpContext.Current.Trace.Write("enter list.BindData");

      if ( this.DataSet.Tables[DataSetTableName.Fields].Rows.Count <= 4 )
      {
        System.Web.HttpContext.Current.Trace.Write("list.BindData, Rows.Count <= 4");

        string message = "No fields defined";
        string format = Utilities.CStrN(DotNetNuke.Services.Localization.Localization.GetString("NoFieldsDefined.ErrorMessage", this.LocalResourceFile), "");

        if ( !string.IsNullOrEmpty(format) )
          message = string.Format(format, this.ModuleContext.EditUrl("Manage"));
        
        PortalModuleBase objControl = (PortalModuleBase)(this.Parent is PortalModuleBase ? this.Parent : this);
        Skin.AddModuleMessage(objControl, message, ModuleMessage.ModuleMessageType.YellowWarning);
      }
      else
      {
        bool MustBind = true;

        System.Web.HttpContext.Current.Trace.Write("list.BindData,has UserDefinedFields");

        if (!Utilities.CBoolN((this.ModuleContext.Settings[SettingName.ShowSearchTextBox]), false))
          this.panSearch.Visible = false;
        
        else if (!this.search.DataBindingNeeded())
        {
          System.Web.HttpContext.Current.Trace.Write((!this.search.DataBindingNeeded()).ToString());
          this.ctlPagingControl.TotalRecords = 0;
          this.ctlPagingControl.Visible = false;
          this.lblNoRecordsFound.Visible = false;
          MustBind = false;
        }

        System.Web.HttpContext.Current.Trace.Write("list.BindData, MustBind = " + (MustBind.ToString()));

        if (MustBind)
        {

          System.Web.HttpContext.Current.Trace.Write("list.BindData, renderMethod" + this.RenderMethod);

          if (this.RenderMethod == SettingName.XslPreDefinedStyleSheet)
            this.BindDataUsingXslTransform((string)this.ModuleContext.Settings[this.RenderMethod]);

          else if (this.RenderMethod == SettingName.XslUserDefinedStyleSheet)
            this.BindDataUsingXslTransform(this.ModuleContext.PortalSettings.HomeDirectory + (string)this.ModuleContext.Settings[this.RenderMethod]);
          
          else
            this.BindDataToDataGrid();
          
        }
      }
      System.Web.HttpContext.Current.Trace.Write("list.BindData done");
    }





    /// <summary>
    ///     BindDataToDataGrid fetchs the data from the database and binds it to the grid
    /// </summary>
    private void BindDataToDataGrid()
    {
      System.Web.HttpContext.Current.Trace.Write("enter list.BindDataToDataGrid");

      string paging;

      this.PopulateDataGridColumns();

      if (this.ModuleContext.Settings.ContainsKey(SettingName.Paging))
        paging = (string)this.ModuleContext.Settings[SettingName.Paging];
      
      else
        paging = string.Empty;

      this.grdData.AllowPaging = !string.IsNullOrEmpty(paging);

      if (!string.IsNullOrEmpty(paging))
        this.grdData.PageSize = int.Parse(paging);
      
      //create a dataview to process the sort
      using (DataView dv = new DataView(this.DataSet.Tables[DataSetTableName.Data]))
      {
        try
        {
          dv.RowFilter = this.GetRowFilter(Utilities.CStrN((this.ModuleContext.Settings[SettingName.Filter]), ""), this.search.Filter());
        }
        catch (Exception e)
        {
          if (ModulePermissionController.CanManageModule(this.ModuleContext.Configuration))
          {
            PortalModuleBase objControl = (PortalModuleBase)(this.Parent is PortalModuleBase ? this.Parent : this);
            Skin.AddModuleMessage(objControl, DotNetNuke.Services.Localization.Localization.GetString("Filter.ErrorMessage", this.LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning);
          }
        }

        ICollection data = dv;

        //sort data view
        if ( !string.IsNullOrEmpty(this.SortField) && !string.IsNullOrEmpty(this.SortOrder) )
          dv.Sort = string.Format("{0} {1}", this.SortField, this.SortOrder);
        
        //Show only Top x rows?
        int topFilter = Utilities.CIntN((this.ModuleContext.Settings[SettingName.TopCount]), 0);

        //if filter, replace data by filtered
        if (topFilter > 0)
        {
          data = new PagedDataSource() 
          {
            DataSource = dv,
            AllowPaging = true,
            PageSize = topFilter,
            CurrentPageIndex = 0
          };
        }

        if (data.Count > 0)
        {
          this.lblNoRecordsFound.Visible = false;

          string UsedCssClasses = Utilities.CStrN((this.ModuleContext.Settings[SettingName.UsedCssClasses]), "");

          if (UsedCssClasses == "DNN")
          {
            this.grdData.AlternatingRowStyle.CssClass = "DataGrid_AlternatingItem";
            this.grdData.RowStyle.CssClass = "DataGrid_Item";
            this.grdData.HeaderStyle.CssClass = "DataGrid_Header";
            this.grdData.BorderWidth = Unit.Pixel(0);
          }
          else if (UsedCssClasses == "YUI")
          {
            this.grdData.CssClass = "tablestyle";
            this.grdData.AlternatingRowStyle.CssClass = "altrowstyle";
            this.grdData.RowStyle.CssClass = "rowstyle";
            this.grdData.HeaderStyle.CssClass = "headerstyle";
            this.grdData.GridLines = GridLines.Both;
          }
          else
            this.grdData.BorderWidth = Unit.Pixel(0);

          if (!string.IsNullOrEmpty(paging))
            this.grdData.PageIndex = (int)Math.Round((double)(Math.Min((double)this.CurrentPage, Math.Ceiling((double)(((double)data.Count) / ((double)this.grdData.PageSize)))) - 1.0));
          
          try
          {
            this.grdData.DataSource = data;
            this.grdData.DataBind();
          }
          catch (FormatException ex)
          {
            this.HandleException(ex, "Databind Exception");
          }
          this.grdData.Visible = true;
          this.ctlPagingControl.Visible = this.grdData.AllowPaging;
          this.ctlPagingControl.PageSize = this.grdData.PageSize;
          this.ctlPagingControl.CurrentPage = this.grdData.PageIndex + 1;
          this.ctlPagingControl.TotalRecords = data.Count;
        }
        else
        {
          if (this.search.IsSearching)
            this.lblNoRecordsFound.Visible = true;
          
          this.ctlPagingControl.TotalRecords = 0;
          this.ctlPagingControl.Visible = false;
        }
      }

      System.Web.HttpContext.Current.Trace.Write("list.BindDataToDataGrid done");

    }





    private void BindDataUsingXslTransform(string StyleSheet)
    {
      try
      {
        this.DataSet.Tables.Add(this.UdtController.Context("", Utilities.CStrN((this.ModuleContext.Settings[SettingName.SortField]), ""), Utilities.CStrN((this.ModuleContext.Settings[SettingName.SortOrder]), ""), (string)this.ModuleContext.Settings[SettingName.Paging]));
        this.FilterDataTable(this.GetRowFilter(Utilities.CStrN((this.ModuleContext.Settings[SettingName.Filter]), ""), this.search.Filter()));
        XslCompiledTransform transform = new XslCompiledTransform();
        transform.Load(HostingEnvironment.MapPath(StyleSheet));
        using (XmlReader reader = new XmlTextReader(new StringReader(this.DataSet.GetXml())))
        {
          using (StringWriter writer = new StringWriter())
          {
            XsltArgumentList arguments = new XsltArgumentList();
            string str = string.Format(Definition.QueryStringParameter.ToLowerInvariant(), this.ModuleContext.ModuleId);

            foreach(string str2 in this.Request.Params.Keys)
              if ((str2 != null) && str2.ToLowerInvariant().StartsWith(str))
                arguments.AddParam(str2.ToLowerInvariant().Substring(str.Length - 5), string.Empty, this.Request[str2]);
            
            
            transform.Transform(reader, arguments, writer);
            this.XslOutput.Controls.Add(new LiteralControl(writer.ToString()));
          }
        }
        this.XslOutput.Visible = true;
      }
      catch (Exception e)
      {

        Exception exc = e;
        this.HandleException(exc, string.Format("{0}<br/>StyleSheet:{1}", DotNetNuke.Services.Localization.Localization.GetString("XslFailed.ErrorMessage", this.LocalResourceFile), StyleSheet));
        this.BindDataToDataGrid();

      }
    }




    private void ctlPagingControl_CurrentPageChanged(object sender, EventArgs evt)
    {
      this.CurrentPage = this.ctlPagingControl.CurrentPage;
    }




    private void FilterDataTable(string filter)
    {
      System.Web.HttpContext.Current.Trace.Write("enter list.FilterDataTable");

      string str = string.Empty;

      if ( !string.IsNullOrEmpty(this.SortField) && !string.IsNullOrEmpty(this.SortOrder) )
        str = string.Format("{0} {1}", this.SortField, this.SortOrder);
      
      DataView view = new DataView(this.DataSet.Tables[DataSetTableName.Data]);
      view.RowFilter = filter;
      view.Sort = str;
      DataTable table = view.ToTable();
      this.DataSet.Tables[DataSetTableName.Data].Clear();
      this.DataSet.Tables[DataSetTableName.Data].Merge(table);
      int num = Utilities.CIntN((this.ModuleContext.Settings[SettingName.TopCount]), 0);

      if (num > 0)
      {
        int num3 = num;

        for (int i = this.DataSet.Tables[DataSetTableName.Data].Rows.Count - 1; i >= num3; i += -1)
          this.DataSet.Tables[DataSetTableName.Data].Rows.RemoveAt(i);
        
      }
      System.Web.HttpContext.Current.Trace.Write("list.FilterDataTable done");
    }




    private string GetFieldTitle(int fieldId)
    {
      DataView view2 = new DataView(this.DataSet.Tables[DataSetTableName.Fields]);
      view2.RowFilter = string.Format("{0}={1}", FieldsTableColumn.Id, fieldId.ToString());
      using (DataView view = view2)
      {
        if (view.Count > 0)
          return (string)view[0][FieldsTableColumn.Title];
        
        return "";
      }
    }




    private string GetRowFilter(string Filter, string Search)
    {
      DotNetNuke.Modules.UserDefinedTable.TokenReplace replace2 = new DotNetNuke.Modules.UserDefinedTable.TokenReplace(true);
      replace2.ModuleInfo = this.ModuleContext.Configuration;
      DotNetNuke.Modules.UserDefinedTable.TokenReplace replace = replace2;

      if ( !string.IsNullOrEmpty(Filter) )
        Filter = replace.ReplaceEnvironmentTokens(Filter);

      if ( !string.IsNullOrEmpty(Filter) && !string.IsNullOrEmpty(Search) )
        return string.Format("{0} AND ({1})", Filter, Search);
      
      return (Filter + Search);
    }




    protected void grdData_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      if ( ((Utilities.CStrN((this.ModuleContext.Settings[SettingName.UsedCssClasses]), "") != "YUI") 
        || string.IsNullOrEmpty(this.SortField)) || string.IsNullOrEmpty(this.SortOrder) )
        return;
      
      int index = -1;

      foreach (DataControlField field in grdData.Columns)
        if (field.SortExpression.StartsWith(this.SortField))
        {
          index = this.grdData.Columns.IndexOf(field);
          break;
        }
      
      if (index > -1)
      {
        TableCell cell;
        if (e.Row.RowType == DataControlRowType.Header)
        {
          cell = e.Row.Cells[index];
          cell.CssClass = cell.CssClass + (string)(this.SortOrder == "ASC" ? " sortascheader" : " sortdescheader");
        }
        else if (e.Row.RowType == DataControlRowType.DataRow)
        {
          cell = e.Row.Cells[index];
          cell.CssClass = cell.CssClass + ((e.Row.RowIndex % 2 == 0) ? "sortaltrow" : "sortrow");
        }
      }
    }




    protected void grdData_Sorting(object sender, GridViewSortEventArgs evt)
    {
      try
      {
        string[] strArray = evt.SortExpression.Split('|');
        string fieldName = strArray[0];

        if (this.IsKnownField(fieldName))
        {
          if (((fieldName == this.SortField) & (this.SortOrder == "ASC")) || ((fieldName != this.SortField) & (strArray[1] == "DESC")))
            this.SortOrder = "DESC";
          
          else
            this.SortOrder = "ASC";
          
          this.SortField = fieldName;
        }
      }
      catch (Exception e)
      {
        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException((PortalModuleBase)this, exc);
      }
    }





    private void HandleException(Exception exc, string LocalizedMessage)
    {
      PortalModuleBase objControl = (PortalModuleBase)(this.Parent is PortalModuleBase ? this.Parent : this);
      ModuleSecurity security = new ModuleSecurity(this.ModuleContext);

      if (security.IsAllowedToAdministrateModule())
      {
        string str = new PortalSecurity().InputFilter(exc.Message, PortalSecurity.FilterFlag.NoScripting);
        Skin.AddModuleMessage(objControl, string.Format("{0}<br/>Error Description: {1}", LocalizedMessage, str), ModuleMessage.ModuleMessageType.YellowWarning);
      }
      DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
    }





    private bool IsKnownField(string fieldName)
    {
      DataTable table = this.DataSet.Tables[DataSetTableName.Fields];
      fieldName = fieldName.Replace("'", "''");

      return (table.Select(string.Format("{0}='{1}'", FieldsTableColumn.Title, fieldName)).Length >= 0);
    }





    /// <summary>
    /// set up Fielddefinitions for Datagrid
    /// </summary>
    private void PopulateDataGridColumns()
    {
      System.Web.HttpContext.Current.Trace.Write("enter list.PopulateDataGridColumns");

      for (int i = this.grdData.Columns.Count - 1; i >= 1; i--)
        this.grdData.Columns.RemoveAt(i);

      BoundField colField;

      //Add Fields dynamically to the grdData
      foreach(DataRow row in DataSet.Tables[DataSetTableName.Fields].Rows)
      {
        colField = new BoundField() 
        {
          HeaderText = (string)row[FieldsTableColumn.Title],
          DataField = (string)row[FieldsTableColumn.Title],
          HtmlEncode = false,
          Visible = Convert.ToBoolean(row[FieldsTableColumn.Visible]),
          SortExpression = string.Format("{0}|ASC", row[FieldsTableColumn.Title].ToString())
        };

        //Add a sorting indicator to the headertext
        if (((Utilities.CStrN((this.ModuleContext.Settings[SettingName.UsedCssClasses]), "") != "YUI")
          && ((string)row[FieldsTableColumn.Title]) == this.SortField) && colField.Visible)
        {
          if (this.SortOrder == "ASC")
            colField.HeaderText += string.Format("<img src=\"{0}/images/sortascending.gif\" border=\"0\" alt=\"Sorted By {1} In Ascending Order\"/>", this.Request.ApplicationPath == "/" ? string.Empty : this.Request.ApplicationPath, this.SortField);
          
          else
            colField.HeaderText += string.Format("<img src=\"{0}/images/sortdescending.gif\" border=\"0\" alt=\"Sorted By {1} In Descending Order\"/>", this.Request.ApplicationPath == "/" ? string.Empty : this.Request.ApplicationPath, this.SortField);
          
        }

        DataType.ByName((string)row[FieldsTableColumn.Type]).SetStylesAndFormats(colField, Utilities.CStrN((row[FieldsTableColumn.OutputSettings]), ""));
        this.grdData.Columns.Add(colField);
      }

      bool EditLinkNeed = false;

      foreach (DataRow row in DataSet.Tables[DataSetTableName.Data].Rows)
      {
        if (!string.IsNullOrEmpty(Utilities.CStrN(row[DataTableColumn.EditLink], "")))
        {
          EditLinkNeed = true;
          break;
        }
      }

      if (!EditLinkNeed)
        this.grdData.Columns.RemoveAt(0);

        System.Web.HttpContext.Current.Trace.Write("list.PopulateDataGridColumns done");
    }





    public void RaisePostBackEvent(string eventArgument)
    {
      ModuleSecurity security = new ModuleSecurity(this.ModuleContext);
      if ((eventArgument == "DeleteAll") && security.IsAllowedToAdministrateModule())
      {
        this.UdtController.DeleteRows();
        this.Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(this.ModuleContext.TabId), true);
      }
    }




    private int CurrentPage
    {
      get
      {
        if (this.ViewState["CurrentPage"] == null)
          return 1;
        
        return (int)this.ViewState["CurrentPage"];
      }
      set
      {
        this.ViewState["CurrentPage"] = value;
      }
    }





    private System.Data.DataSet DataSet
    {
      get
      {
        System.Web.HttpContext.Current.Trace.Write("enter list.DataSet get");

        if (this.objDataSet == null)
        {
          System.Web.HttpContext.Current.Trace.Write("list.DataSet is null");
          this.objDataSet = this.UdtController.GetDataSet();
        }

        System.Web.HttpContext.Current.Trace.Write("list.DataSet get done");

        return this.objDataSet;
      }
    }




    ModuleActionCollection DotNetNuke.Entities.Modules.IActionable.ModuleActions
    {
      get
      {
        System.Web.HttpContext.Current.Trace.Write("enter list.ModuleActions get");

        ModuleActionCollection actions = new ModuleActionCollection();
        try
        {
          ModuleSecurity security = new ModuleSecurity(this.ModuleContext);

          //Has more columns than the system default columns (Created/by/at, Changed by/at)
          try
          {
            if (Utilities.CStrN((this.Settings[SettingName.ListOrForm]), "") == "Form")
              actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("BackToForm.Action", this.LocalResourceFile), "AddContent.Action", "", "~/images/rew.gif", DotNetNuke.Common.Globals.NavigateURL(this.ModuleContext.TabId), false, SecurityAccessLevel.View, true, false);
            
            else if (((!Utilities.CStrN((this.Settings[SettingName.ListOrForm]), "").Contains("Form") 
              && security.IsAllowedToAddRow()) && (this.DataSet.Tables[DataSetTableName.Fields].Rows.Count > 4)) 
              && (security.IsAllowedToAdministrateModule() || ModuleSecurity.HasAddPermissonByQuota(this.DataSet.Tables[DataSetTableName.Fields], this.DataSet.Tables[DataSetTableName.Data], Utilities.CIntN((this.ModuleContext.Settings[SettingName.UserRecordQuota])), this.ModuleContext.PortalSettings.UserInfo.Username)))

              actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("AddContent.Action", this.LocalResourceFile), "AddContent.Action", "", "~/images/add.gif", this.ModuleContext.EditUrl(), false, SecurityAccessLevel.View, true, false);
            
          }
          catch (Exception e)
          { }

          actions.Add(
            this.ModuleContext.GetNextActionID()
            , DotNetNuke.Services.Localization.Localization.GetString("ShowXML.Action", this.LocalResourceFile)
            , "", ""
            , this.ResolveUrl("~/images/XML.gif")
            , this.ResolveUrl(string.Format("~{0}ShowXml.ashx", Definition.PathOfModule)) + "?tabid=" + this.ModuleContext.TabId + "&mid=" + (string)this.ModuleContext.ModuleId.ToString()
            , false, SecurityAccessLevel.Edit, true, true
          );

          if (this.DataSet.Tables[DataSetTableName.Data].Rows.Count > 0)
          {
            string postBackEventReference = this.Page.ClientScript.GetPostBackEventReference(this, "DeleteAll");
            postBackEventReference = string.Format("javascript:if (confirm('{0}')) {1}", Utilities.CStrN(DotNetNuke.Services.Localization.Localization.GetString("DeleteAll.Confirm", this.LocalResourceFile), "").Replace("'", @"\'"), postBackEventReference);
            actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("DeleteAll.Action", this.LocalResourceFile), "", "", this.ResolveUrl("~/images/delete.gif"), postBackEventReference, false, SecurityAccessLevel.Edit, true, false);
          }

          if (("UDT_" + Utilities.CStrN((this.ModuleContext.Settings[SettingName.RenderingMethod]), "")) == SettingName.XslUserDefinedStyleSheet)
            actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("EditXsl.Action", this.LocalResourceFile), "", "", this.ResolveUrl("~/images/action_settings.gif"), this.ModuleContext.EditUrl("Edit", "Current", "GenerateXsl"), false, SecurityAccessLevel.Edit, true, false);
          
        }
        catch (Exception ex)
        {
          DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
        }

        System.Web.HttpContext.Current.Trace.Write("list.ModuleActions get done");

        return actions;
      }
    }




    //protected virtual GridView grdData
    //{
    //  get
    //  {
    //    return this._grdData;
    //  }
    //  [MethodImpl(MethodImplOptions.Synchronized)]
    //  set
    //  {
    //    GridViewRowEventHandler handler = new GridViewRowEventHandler(this.grdData_RowDataBound);
    //    GridViewSortEventHandler handler2 = new GridViewSortEventHandler(this.grdData_Sorting);
    //    if (this._grdData != null)
    //    {
    //      this._grdData.RowDataBound -= handler;
    //      this._grdData.Sorting -= handler2;
    //    }
    //    this._grdData = value;
    //    if (this._grdData != null)
    //    {
    //      this._grdData.RowDataBound += handler;
    //      this._grdData.Sorting += handler2;
    //    }
    //  }
    //}




    //protected virtual Label lblNoRecordsFound
    //{
    //  get
    //  {
    //    return this._lblNoRecordsFound;
    //  }
    //  [MethodImpl(MethodImplOptions.Synchronized)]
    //  set
    //  {
    //    this._lblNoRecordsFound = value;
    //  }
    //}





    public ModuleActionCollection ModuleActions
    {
      get
      {
        ModuleActionCollection actions = new ModuleActionCollection();
        try
        {
          ModuleSecurity security = new ModuleSecurity(this.ModuleContext);
          try
          {
            if (Utilities.CStrN((this.Settings[SettingName.ListOrForm]), "") == "Form")
              actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("BackToForm.Action", this.LocalResourceFile), "AddContent.Action", "", "~/images/rew.gif", DotNetNuke.Common.Globals.NavigateURL(this.ModuleContext.TabId), false, SecurityAccessLevel.View, true, false);
            
            else if (((!Utilities.CStrN((this.Settings[SettingName.ListOrForm]), "").Contains("Form") && security.IsAllowedToAddRow()) && (this.DataSet.Tables[DataSetTableName.Fields].Rows.Count > 4)) && (security.IsAllowedToAdministrateModule() || ModuleSecurity.HasAddPermissonByQuota(this.DataSet.Tables[DataSetTableName.Fields], this.DataSet.Tables[DataSetTableName.Data], Utilities.CIntN((this.ModuleContext.Settings[SettingName.UserRecordQuota])), this.ModuleContext.PortalSettings.UserInfo.Username)))
              actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("AddContent.Action", this.LocalResourceFile), "AddContent.Action", "", "~/images/add.gif", this.ModuleContext.EditUrl(), false, SecurityAccessLevel.View, true, false);
            
          }
          catch (Exception e)
          { }

          actions.Add(
            this.ModuleContext.GetNextActionID()
            , DotNetNuke.Services.Localization.Localization.GetString("ShowXML.Action", this.LocalResourceFile)
            , "", "", this.ResolveUrl("~/images/XML.gif")
            , this.ResolveUrl(string.Format("~{0}ShowXml.ashx", Definition.PathOfModule)) + "?tabid=" + this.ModuleContext.TabId.ToString() + "&mid=" + this.ModuleContext.ModuleId.ToString()
            , false, SecurityAccessLevel.Edit, true, true
          );

          if (this.DataSet.Tables[DataSetTableName.Data].Rows.Count > 0)
          {
            string postBackEventReference = this.Page.ClientScript.GetPostBackEventReference(this, "DeleteAll");
            postBackEventReference = string.Format("javascript:if (confirm('{0}')) {1}", Utilities.CStrN(DotNetNuke.Services.Localization.Localization.GetString("DeleteAll.Confirm", this.LocalResourceFile), "").Replace("'", @"\'"), postBackEventReference);
            actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("DeleteAll.Action", this.LocalResourceFile), "", "", this.ResolveUrl("~/images/delete.gif"), postBackEventReference, false, SecurityAccessLevel.Edit, true, false);
          }

          if (("UDT_" + Utilities.CStrN((this.ModuleContext.Settings[SettingName.RenderingMethod]), "")) == SettingName.XslUserDefinedStyleSheet)
            actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("EditXsl.Action", this.LocalResourceFile), "", "", this.ResolveUrl("~/images/action_settings.gif"), this.ModuleContext.EditUrl("Edit", "Current", "GenerateXsl"), false, SecurityAccessLevel.Edit, true, false);
          
        }
        catch (Exception exception2)
        {
          Exception exc = exception2;
          DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
        }

        return actions;
      }
    }




    //protected virtual Panel panSearch
    //{
    //  get
    //  {
    //    return this._panSearch;
    //  }
    //  [MethodImpl(MethodImplOptions.Synchronized)]
    //  set
    //  {
    //    this._panSearch = value;
    //  }
    //}




    //protected virtual PlaceHolder phSearchSentence
    //{
    //  get
    //  {
    //    return this._phSearchSentence;
    //  }
    //  [MethodImpl(MethodImplOptions.Synchronized)]
    //  set
    //  {
    //    this._phSearchSentence = value;
    //  }
    //}




    //protected virtual LabelControl plSearch
    //{
    //  get
    //  {
    //    return this._plSearch;
    //  }
    //  [MethodImpl(MethodImplOptions.Synchronized)]
    //  set
    //  {
    //    this._plSearch = value;
    //  }
    //}




    private string RenderMethod
    {
      get
      {
        return string.Format("UDT_{0}", Utilities.CStrN((this.ModuleContext.Settings[SettingName.RenderingMethod]), ""));
      }
    }




    private string SortField
    {
      get
      {
        int tmp;
        if (this.ViewState["SortField"] == null && int.TryParse((string)this.ModuleContext.Settings[SettingName.SortField], out tmp))
          this.ViewState["SortField"] = this.GetFieldTitle(tmp);
        
        return (string)this.ViewState["SortField"];
      }
      set
      {
        this.ViewState["SortField"] = value;
      }
    }





    private string SortOrder
    {
      get
      {
        if (this.ViewState["SortOrder"] == null)
          return (string)this.ModuleContext.Settings[SettingName.SortOrder];
        
        return (string)this.ViewState["SortOrder"];
      }
      set
      {
        this.ViewState["SortOrder"] = value;
      }
    }





    private UserDefinedTableController UdtController
    {
      get
      {
        if (this._udtController == null)
          this._udtController = new UserDefinedTableController(this.ModuleContext);

        return this._udtController;
      }
    }





    //protected virtual PlaceHolder XslOutput
    //{
    //  get
    //  {
    //    return this._XslOutput;
    //  }
    //  [MethodImpl(MethodImplOptions.Synchronized)]
    //  set
    //  {
    //    this._XslOutput = value;
    //  }
    //}





    protected string createLink(object container)
    {
      //return DataBinder.Eval(container, "DataItem.EditLink", "<a href='{0}'><img src='" + DotNetNuke.Common.Globals.ResolveUrl("~/images/edit.gif") + "&quot; alt='edit' border='0'/></a>");
      return "<a href='" + (string)container + "'><img src='" + DotNetNuke.Common.Globals.ResolveUrl("~/images/edit.gif") + "' alt='edit' border='0'/></a>";
      //return container.ToString();
    }



  }

}

